import { ref } from "vue";
import { defineStore } from "pinia";
import type { RouteRecordRaw } from "vue-router";
import { constantRoutes } from "@/router";

const modules = import.meta.glob('../../views/**/*.vue');
const Layout = () => import("@/layout/index.vue");

// setup
export const usePermissionStore = defineStore('permission', () => {
    // state
    const routes = ref<RouteRecordRaw[]>([])

    const isDynamicAdded = ref(false)

    function setDynamicAdded(val: boolean) {
    isDynamicAdded.value = val
    }

    // actions
    function setRoutes(newRoutes: RouteRecordRaw[]){
        routes.value = constantRoutes.concat(newRoutes);
    }


    /**
     * 递归过滤有权限的异步(动态)路由
     * @param routes 后台获取的路由
     * @returns 
     */
    const filterAsyncRoutes = (routes: RouteRecordRaw[]) => {
        const asyncRoutes: RouteRecordRaw[] = [];
        
        routes.forEach((route) => {
            const tmpRoute = { ...route };  // ES6扩展运算符复制新对象
            if(!route.name){
                tmpRoute.name = tmpRoute.path;
            }
            // 组件名称转换成真实组件
            if(tmpRoute.component?.toString() === 'Layout'){
                tmpRoute.component = Layout
            } else {
                const component = modules[`../../views/${tmpRoute.component}.vue`];
                if(component){
                    tmpRoute.component = component;
                } else {
                    tmpRoute.component = modules[`../../views/error-page/404.vue`];
                }
            }

            if(tmpRoute.children){
                tmpRoute.children = filterAsyncRoutes(tmpRoute.children);
            }

            asyncRoutes.push(tmpRoute);
        })

        return asyncRoutes;
    }

    // 放在 usePermissionStore 外部，作为模块级变量
    const mockAsyncRoutes: any[] = [
        {
            "path": "/farmManagement",
            "component": "Layout",
            "redirect": "/farmManagement/index",
            "name": "farmManagement",
            "meta": {
                "title": "农场管理",
                "icon": "farm",
                "hidden": false,
                "alwaysShow": false,
                "params": null
            },
            "children": [
                {
                    "path": "index",
                    "component": "farmManagement/index",
                    "name": "farmManagementIndex",
                    "meta": {
                        "title": "农场管理",
                        "icon": "farm",
                        "hidden": false,
                        "keepAlive": true,
                        "alwaysShow": false,
                        "params": null
                    }
                },
                // 农场详情页，作为farmManagement的直接子路由，而不是index的子路由
                {
                    "path": "index/farmDetail",
                    "component": "farmManagement/farmDetail",
                    "name": "farmDetail",
                    "meta": {
                        "title": "农场详情",
                        "hidden": true  // 设置为true，不在侧边栏显示
                    }
                }
            ]
        },
        {
            "path": "/deviceManagement",
            "component": "Layout",
            "redirect": "/deviceManagement/index",
            "name": "/deviceManagement",
            "meta": {
                "title": "设备管理",
                "icon": "device",
                "hidden": false,
                "alwaysShow": false,
                "params": null
            },
            "children": [
                {
                    "path": "index",
                    "component": "deviceManagement/index",
                    "name": "deviceManagementIndex",
                    "meta": {
                        "title": "设备管理",
                        "icon": "device",
                        "hidden": false,
                        "keepAlive": true,
                        "alwaysShow": false,
                        "params": null
                    }
                }
            ]
        },
        {
        "path": "/taskManagement",
        "component": "Layout",
        // "redirect": "/taskManagement/config",
        "name": "/taskManagement",
        "meta": {
            "title": "任务管理",
            "icon": "task",
            "hidden": false,
            "alwaysShow": false,
            "params": null
        },
        "children": [
            {
                "path": "config",
                "component": "taskManagement/config/index",
                "name": "taskManagementConfig",
                "meta": {
                    "title": "任务配置",
                    // "icon": "el-icon-User",
                    "hidden": false,
                    "keepAlive": true,
                    "alwaysShow": false,
                    "params": null
                },
                "children": [
                    {
                        "path": "configDetail",
                        // "component": "taskManagement/config/ConfigDetail",
                        "component": "taskManagement/config/components/ConfigDetail",
                        "name": "taskConfigDetail",
                        "meta": {
                            "title": "任务详情",
                            "hidden": true  // 设置为true，不在侧边栏显示
                        }
                    }
                ]
            },
            {
                "path": "data",
                "component": "taskManagement/data/index",
                "name": "taskManagementData",
                "meta": {
                    "title": "任务数据",
                    // "icon": "el-icon-goods",
                    "hidden": false,
                    "keepAlive": true,
                    "alwaysShow": false,
                    "params": null
                }
            },
            {
                "path": "plan",
                "component": "taskManagement/plan/index",
                "name": "taskManagementPlan",
                "meta": {
                    "title": "任务计划",
                    // "icon": "el-icon-menu",
                    "hidden": false,
                    "keepAlive": true,
                    "alwaysShow": false,
                    "params": null
                }
            },
        ]
        },
        {
            "path": "/userManagement",
            "component": "Layout",
            "redirect": "/userManagement/index",
            "name": "/userManagement",
            "meta": {
                "title": "用户管理",
                "icon": "user",
                "hidden": false,
                "alwaysShow": false,
                "params": null
            },
            "children": [
                {
                    "path": "index",
                    "component": "userManagement/index",
                    "name": "userManagementIndex",
                    "meta": {
                        "title": "用户管理",
                        "icon": "user",
                        "hidden": false,
                        "keepAlive": true,
                        "alwaysShow": false,
                        "params": null
                    }
                }
            ]
        },
    ];

    /**
     * 生成路由
     * @param roles 用户角色
     * @returns {Array} 生成的路由
     */
    function generateRoutes(){
        return new Promise<RouteRecordRaw[]>((resolve) => {
            let accessedRoutes: RouteRecordRaw[] = filterAsyncRoutes(mockAsyncRoutes);
            setRoutes(accessedRoutes);
            resolve(accessedRoutes);
        })
    }

    /**
     * 获取与激活的顶部菜单项相关的混合模式左侧菜单集合
     */
    const mixLeftMenus = ref<RouteRecordRaw[]>([]);
    function setMixLeftMenus(topMenuPath: string){
        const matchedItem = routes.value.find((item) => item.path === topMenuPath);
        if (matchedItem && matchedItem.children) {
            mixLeftMenus.value = matchedItem.children;
        }
    }



    return {
        routes,
        isDynamicAdded,
        setDynamicAdded,
        setRoutes,
        generateRoutes,
        setMixLeftMenus
    }
});